﻿using Modbus.Device;
using Sunny.UI;
using Sunny.UI.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;


namespace DeltaPlcSystem
{
    public partial class Form1 : Form
    {
        //强制释放进程
        [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
        public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
      
        private delegate void ThreadDelegate(DeviceClass dc);
        Dictionary<string, PlcControl> ipAsahDic=new Dictionary<string, PlcControl>();//控件字典
        List<DeviceClass> deviceList = new List<DeviceClass>();//设备集合

        public static List<Thread> threadList = new List<Thread>();//设备集合


        public static List<SimulatorDevice> MachineList = new List<SimulatorDevice>();//设备集合

        public static int UpTime = 1000;//上传更新时间
        public static int TbsTime = 0;//上传更新时间
        public static string PQMserverURL = string.Empty;
        public static double LogSize = 0d;
        public static string Password = string.Empty;


        public static string StartTime = string.Empty;
        public static string EndTime = string.Empty;

        public static bool TotalControl=false;//运行中禁止操作
        DirectoryInfo di;//获取设备路径
        DirectoryInfo logDi;//获取设备路径
        DirectoryInfo machineDi;//获取设备路径
        string timePath = string.Empty;


        string MachinePath = string.Empty;

        public Form1()
        {
           
            InitializeComponent();
            MaximizeBox = false;
            FormBorderStyle = FormBorderStyle.FixedDialog;
            Text = "DeltaDcSystem V2.2.2";
            uiLabel1.Text = "当前用户：";
            timer1.Start();
         
            pictureBox1.BackgroundImage = Properties.Resources.logo;
            StartToolStripMenuItem.Image = Properties.Resources.play_one;
            StopToolStripMenuItem.Image = Properties.Resources.pause;
            DeviceToolStripMenuItem.Image = Properties.Resources.iMac;
            EnableToolStripMenuItem.Image = Properties.Resources.application;
            UpdateToolStripMenuItem.Image = Properties.Resources.update;
            HelpToolStripMenuItem.Image = Properties.Resources.help;

            StartToolStripMenuItem.Click += StartToolStripMenuItem_Click;
            StopToolStripMenuItem.Click += StopToolStripMenuItem_Click;
            toolStripMenuItem1.Click += toolStripMenuItem1_Click;
            toolStripMenuItem2.Click += toolStripMenuItem2_Click;
            toolStripMenuItem3.Click += toolStripMenuItem3_Click;

            AddPLCToolStripMenuItem.Click += AsahserielsToolStripMenuItem_Click;
            DeletePLCToolStripMenuItem.Click += DeletePLCToolStripMenuItem_Click;
            pQMToolStripMenuItem.Click += PQMToolStripMenuItem_Click;
            postTimeToolStripMenuItem.Click += UpLoadTimeToolStripMenuItem_Click;
            tBSToolStripMenuItem.Click += TBSToolStripMenuItem_Click;
            AutoStartToolStripMenuItem.Click += AutoStartToolStripMenuItem_Click;
            ChangePwToolStripMenuItem.Click += ChangePwToolStripMenuItem_Click;
            LogToolStripMenuItem.Click += LogToolStripMenuItem_Click;

            iNTERVALToolStripMenuItem.Click += INTERVALToolStripMenuItem_Click;


            timePath = Application.StartupPath + @"\GlobalParameters.xml";
            di = new DirectoryInfo(Application.StartupPath + @"\Device");
            logDi= new DirectoryInfo(Application.StartupPath + @"\Log");
            machineDi = new DirectoryInfo(Application.StartupPath + @"\Delta");
            IniGlobalPara();
            IniDeviceInfo();
            CreateLogInfo();
            StartThread();
        
        }

        private void INTERVALToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IntervalForm intervalForm = new IntervalForm();
            intervalForm.IntervalEvent += IntervalForm_IntervalEvent;
            intervalForm.ShowDialog();
        }

        private void IntervalForm_IntervalEvent(string startTime1, string endTime1)
        {
            try
            {
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(timePath);
                XmlNodeList xmlNode = xmlDocument.SelectSingleNode("GlobalParameters").ChildNodes;

                foreach (XmlNode node in xmlNode)
                {
                   
                        if (node.Name.ToLower() == "starttime")
                        {
                            node.InnerText = startTime1;
                            xmlDocument.Save(timePath);

                        StartTime = startTime1;
                        }
                   
                       else if (node.Name.ToLower() == "endtime")
                        {
                            node.InnerText = endTime1;
                            xmlDocument.Save(timePath);

                        EndTime = endTime1; 
                        }
                    

                }
            }
            catch { MessageBox.Show("数据写入异常"); }
        }

        private void TBSToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TimeForm timeForm = new TimeForm(1);
            timeForm.TimeEvent += TimeForm_TimeEvent;
            timeForm.ShowDialog();
        }

        public void CreateLogInfo()
        {
            try
            {
                if (deviceList.Count > 0)
                {
                    for (int i = 0; i < deviceList.Count; i++)
                    {
                        string path = Application.StartupPath + @"\Log\" + deviceList[i].Ip + ".txt";
                        if (!File.Exists(path))
                        {
                            using (StreamWriter sw = File.CreateText(path))
                            {
                                deviceList[i].LogPath = path;
                            }
                        }
                        else
                        {
                            deviceList[i].LogPath = path;
                        }
                    }
                }             
            }
            catch { }   
        }

        public void IniGlobalPara()
        {
            try
            {
                FileInfo[] files = machineDi.GetFiles();

                foreach (FileInfo item in files)
                {
                    if (item.Extension.ToLower() == ".txt")
                    {
                        SimulatorDevice device = new SimulatorDevice();
                        device.MachineName = item.Name.Split('.')[0];
                        string[] TempAp = File.ReadAllLines(item.FullName);

                        for (int i = 0; i < TempAp.Length; i++)
                        {
                            device.MachineIdList.Add(TempAp[i]);
                        }


                        MachineList.Add(device);    
                    }
                }
            }
            catch { }


            try
            {
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(timePath);
                XmlNodeList xmlNode = xmlDocument.SelectSingleNode("GlobalParameters").ChildNodes;

                foreach (XmlNode item in xmlNode)
                {
                    if (item.Name.ToLower() == "posttime")
                    {
                        UpTime = int.Parse(item.InnerText);
                    }
                    else if (item.Name.ToLower() == "tbstime")
                    {
                        TbsTime = int.Parse(item.InnerText);
                    }
                    else if (item.Name.ToLower() == "pqmserverurl")
                    {
                        PQMserverURL = item.InnerText;
                    }                 
                    else if (item.Name.ToLower() == "logsize")
                    {
                        LogSize = Convert.ToDouble(item.InnerText);
                    }
                    else if (item.Name.ToLower() == "password")
                    {
                        Password = item.InnerText;
                    }
                    else if (item.Name.ToLower() == "starttime")
                    {
                        StartTime = item.InnerText;
                    }
                    else if (item.Name.ToLower() == "endtime")
                    {
                        EndTime = item.InnerText;
                    }
                }
               
            }
            catch { MessageBox.Show("数据读取异常"); }
       
        }
        /// <summary>
        /// 初始化设备信息
        /// </summary>
        public void IniDeviceInfo()
        {

            FileInfo[] files = di.GetFiles();

            foreach (FileInfo item in files)
            {
                if (item.Extension.ToLower() == ".xml")
                {
                    TabPage tempPage = new TabPage();   
                    DeviceClass tempDevice = new DeviceClass();


                    XmlDocument xmlDocument = new XmlDocument();
                    xmlDocument.Load(item.FullName);
                    XmlNodeList xmlNode= xmlDocument.SelectSingleNode("PLCDATA").ChildNodes;

                    foreach (XmlNode node in xmlNode)
                    {
                        if (node.Name=="ClientIP")
                        {
                            tempDevice.Ip = node.InnerText;
                        }
                        else if (node.Name == "InterfaceID")
                        {
                            tempDevice.InterfaceID = node.InnerText;
                        }
                        else if (node.Name == "EquipName")
                        {
                            tempDevice.EquipName = node.InnerText;
                        }
                        else if (node.Name == "EquipType")
                        {
                            tempDevice.EquipType = node.InnerText;
                        }
                        else if (node.Name == "Status")
                        {
                            tempDevice.Status = node.InnerText;
                        }
                        else if (node.Name == "StatusCode")
                        {
                            tempDevice.StatusCode = node.InnerText;
                        }
                        else if (node.Name == "PassQty")
                        {
                            tempDevice.PassQty = node.InnerText;
                        }
                        else if (node.Name == "FailQty")
                        {
                            tempDevice.FailQty = node.InnerText;
                        }
                        else if (node.Name == "ErrorCnt")
                        {
                            tempDevice.ErrorCnt = node.InnerText;
                        }
                        else if (node.Name == "ErrorTimes")
                        {
                            tempDevice.ErrorTimes = node.InnerText;
                        }
                        else if (node.Name == "CycleTime")
                        {
                            tempDevice.CycleTime = node.InnerText;
                        }
                        else if (node.Name == "RunningTime")
                        {
                            tempDevice.RunningTime = node.InnerText;
                        }
                        else if (node.Name == "WaitingTime")
                        {
                            tempDevice.WaitingTime = node.InnerText;
                        }
                        else if (node.Name == "SelfCheck")
                        {
                            tempDevice.SelfCheck = node.InnerText;
                        }
                        else if (node.Name == "InputQty")
                        {
                            tempDevice.InputQty = node.InnerText;
                        }
                        else if (node.Name == "Barcode")
                        {
                            tempDevice.Barcode = node.InnerText;
                        }
                        else if (node.Name == "Model")
                        {
                            tempDevice.Model = node.InnerText;
                        }
                        else if (node.Name == "CT_Q")
                        {
                            tempDevice.CT_Q = node.InnerText;
                        }
                        else if (node.Name == "CT_M")
                        {
                            tempDevice.CT_M = node.InnerText;
                        }
                        else if (node.Name == "IsEnable")
                        {
                            tempDevice.IsEnable = node.InnerText;
                        }
                        else if (node.Name == "PlcMode")
                        {
                            tempDevice.PlcMode = node.InnerText;
                        }
                        else if (node.Name == "ModulusValue")
                        {
                            try
                            { tempDevice.ModulusValue = Convert.ToDouble(node.InnerText); }
                            catch { }
                           
                        }
                        else if (node.Name == "VirtualMachine")
                        {
                            try
                            { tempDevice.VirtualMachine = node.InnerText; }
                            catch { }

                        }
                        else if (node.Name == "IsTimeEnable")
                        {
                            try
                            { 
                                if (node.InnerText=="1")
                                tempDevice.IsTimeEnable = true; 
                                else 
                                    tempDevice.IsTimeEnable = false;
                            }
                            catch { }

                        }
                    }
              
                    if (tempDevice.IsEnable.ToLower() == "0")
                        tempPage.Text = "✘ " + item.Name.Replace(".xml", "");
                    else
                    {
                        tempPage.Text = "✔ " + item.Name.Replace(".xml", "");
                    }

                
                    PlcControl tempControl = new PlcControl(tempDevice);
                    tempControl.Dock = DockStyle.Fill;
                    tempPage.Controls.Add(tempControl);
                    deviceUiTabControlMenu.TabPages.Add(tempPage);
                    ipAsahDic.Add(tempDevice.Ip, tempControl);
                    deviceList.Add(tempDevice);

                    ToolStripMenuItem tempTool = new ToolStripMenuItem();
                    tempTool.Text = tempDevice.Ip;
                    tempTool.Click += TempTool_Click;
                    UpdatePLCToolStripMenuItem.DropDownItems.Add(tempTool);
                }
            }


            if (deviceList.Count > 50)
            {
                MessageBox.Show("超过设备限制50，请前往配置文件删除，程序退出！","警告");
                Environment.Exit(0);
            }

        }

        #region 毫秒延时
        public static void Delay(int mm)
        {
            DateTime current = DateTime.Now;
            while (current.AddMilliseconds(mm) > DateTime.Now)
            {
                try
                {
                    Thread.Sleep(1);//防止CPU
                    Application.DoEvents();
                }
                catch { continue; }
              
            }
        }
        #endregion

        private void StartThread()
        {
            if (deviceList.Count > 0)
            {
                for (int i = 0; i < deviceList.Count; i++)
                {
                    if (deviceList[i].IsEnable == "1")
                    {
                        if (!deviceList[i].IsThreadRun)
                        {
                            deviceList[i].PlcModbus = new ModbusTcp();


                            Thread thread = new Thread(new ParameterizedThreadStart(ipAsahDic[deviceList[i].Ip].ReadPlcThread));
                            thread.Name = deviceList[i].Ip;
                            thread.IsBackground = true;                         
                            thread.Start(deviceList[i]);
                            
                            threadList.Add(thread);


                            deviceList[i].IsThreadRun = true;

                        }

                        deviceList[i].IsReadData = true;

                    }
                }

                StartToolStripMenuItem.Enabled = false;

                TotalControl = true;
            }

         
        }
 
    
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {            
                Environment.Exit(0);           
            }
            catch
            { }
        
        }


        #region 按钮事件
        private void TempTool_Click(object sender, EventArgs e)
        {
            if (TotalControl)
            {
                MessageBox.Show("运行中禁止更新设备");
                return;
            }

            ToolStripMenuItem tempStrip = (ToolStripMenuItem)sender;


            for (int i = 0; i < deviceList.Count; i++)
            {
                if (tempStrip.Text.Trim() == deviceList[i].Ip)
                {
                    PlcForm asAhForm = new PlcForm(1, deviceList[i]);
                    asAhForm.AddEvent += Aaf_AsahAddEvent;
                    asAhForm.ShowDialog();

                    break;
                }
            }


        }

        private void UpLoadTimeToolStripMenuItem_Click(object sender, EventArgs e)
        {
       
            TimeForm timeForm = new TimeForm(0);
            timeForm.TimeEvent += TimeForm_TimeEvent;
            timeForm.ShowDialog();          
        }

        private void PQMToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (TotalControl)
            {
                MessageBox.Show("运行中禁止更新");
                return;
            }
            UrlForm timeForm = new UrlForm();
            timeForm.UrlEvent += TimeForm_UrlEvent;
            timeForm.ShowDialog();
        }

        private void TimeForm_UrlEvent()
        {
           
                try
                {
                    XmlDocument xmlDocument = new XmlDocument();
                    xmlDocument.Load(timePath);
                    XmlNodeList xmlNode = xmlDocument.SelectSingleNode("GlobalParameters").ChildNodes;

                    foreach (XmlNode node in xmlNode)
                    {
                        if (node.Name.ToLower() == "pqmserverurl")
                        {
                            node.InnerText = PQMserverURL;
                            xmlDocument.Save(timePath);
                        }
                    }

                }
                catch { MessageBox.Show("数据写入异常"); }


                if (ipAsahDic.Count > 0)
                {
                    foreach (string item in ipAsahDic.Keys)
                    {
                        ipAsahDic[item].Txt_Server.Text = PQMserverURL;
                    }
                }
          
        }

        private void AutoStartToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {

                bool isClose = PublicClass.SetMeStart(false);
                bool isOpen = PublicClass.SetMeStart(true);
                if (isOpen)
                {
                    if (isClose)
                    {
                        MessageBox.Show("dele开机自启成功");
                    }
                    else
                    {
                        MessageBox.Show("开机自启成功");
                    }
                }
                else
                {
                    MessageBox.Show("开机自启失败");
                }
            }
            catch { }

        }

        private void TimeForm_TimeEvent(int mode)
        {
            try
            {
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(timePath);
                XmlNodeList xmlNode = xmlDocument.SelectSingleNode("GlobalParameters").ChildNodes;

                foreach (XmlNode node in xmlNode)
                {
                    if (mode == 0)
                    {
                        if (node.Name.ToLower() == "posttime")
                        {
                            node.InnerText = UpTime.ToString();
                            xmlDocument.Save(timePath);
                        }
                    }
                    else
                    {
                        if (node.Name.ToLower() == "tbstime")
                        {
                            node.InnerText = TbsTime.ToString();
                            xmlDocument.Save(timePath);
                        }
                    }

                }
            }
            catch { MessageBox.Show("数据写入异常"); }


            if (ipAsahDic.Count > 0)
            {
                foreach (string item in ipAsahDic.Keys)
                {
                    ipAsahDic[item].uiTextBox22.Text = UpTime.ToString();
                }
            }
         
        }
      
        private void AsahserielsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (TotalControl)
            {
                MessageBox.Show("运行中禁止添加设备");
                return;
            }

            PlcForm aaf = new PlcForm(0);
            aaf.AddEvent += Aaf_AsahAddEvent;
            aaf.ShowDialog();

        }

        private void Aaf_AsahAddEvent(List<string> tempData,int mode)
        {
            if (mode == 0)
            {
                if (deviceList.Count > 50)
                {
                    MessageBox.Show("设备限制50以内，请删除设备");
                    return;
                }


                FileInfo[] files = di.GetFiles();

                foreach (FileInfo item in files)
                {
                    if (item.Name.Replace(".xml", "") == tempData[0])
                    {
                        MessageBox.Show("此设备IP已存在");
                        return;
                    }
                }

                XmlDocument xmlDoc = new XmlDocument();
                XmlDeclaration xmlDeclar;
                xmlDeclar = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
                xmlDoc.AppendChild(xmlDeclar);

                XmlElement xmlElement = xmlDoc.CreateElement("", "PLCDATA", "");
                xmlDoc.AppendChild(xmlElement);


                for (int i = 0; i < 25; i++)
                {
                    if (i == 0)
                    {
                        XmlElement xeSub = xmlDoc.CreateElement("ClientIP");
                        xeSub.InnerText = tempData[i];
                        xmlElement.AppendChild(xeSub);
                    }
                    else if (i == 1)
                    {
                        XmlElement xeSub = xmlDoc.CreateElement("InterfaceID");
                        xeSub.InnerText = tempData[i];
                        xmlElement.AppendChild(xeSub);
                    }
                    else if (i == 2)
                    {
                        XmlElement xeSub = xmlDoc.CreateElement("EquipName");
                        xeSub.InnerText = tempData[i];
                        xmlElement.AppendChild(xeSub);
                    }
                    else if (i == 3)
                    {
                        XmlElement xeSub = xmlDoc.CreateElement("EquipType");
                        xeSub.InnerText = tempData[i];
                        xmlElement.AppendChild(xeSub);
                    }
                    else if (i == 4)
                    {
                        XmlElement xeSub = xmlDoc.CreateElement("Status");
                        xeSub.InnerText = tempData[i];
                        xmlElement.AppendChild(xeSub);
                    }
                    else if (i == 5)
                    {
                        XmlElement xeSub = xmlDoc.CreateElement("StatusCode");
                        xeSub.InnerText = tempData[i];
                        xmlElement.AppendChild(xeSub);
                    }
                    else if (i == 6)
                    {
                        XmlElement xeSub = xmlDoc.CreateElement("PassQty");
                        xeSub.InnerText = tempData[i];
                        xmlElement.AppendChild(xeSub);
                    }
                    else if (i == 7)
                    {
                        XmlElement xeSub = xmlDoc.CreateElement("FailQty");
                        xeSub.InnerText = tempData[i];
                        xmlElement.AppendChild(xeSub);
                    }
                    else if (i == 8)
                    {
                        XmlElement xeSub = xmlDoc.CreateElement("ErrorCnt");
                        xeSub.InnerText = tempData[i];
                        xmlElement.AppendChild(xeSub);
                    }
                    else if (i == 9)
                    {
                        XmlElement xeSub = xmlDoc.CreateElement("ErrorTimes");
                        xeSub.InnerText = tempData[i];
                        xmlElement.AppendChild(xeSub);
                    }
                    else if (i == 10)
                    {
                        XmlElement xeSub = xmlDoc.CreateElement("CycleTime");
                        xeSub.InnerText = tempData[i];
                        xmlElement.AppendChild(xeSub);
                    }
                    else if (i == 11)
                    {
                        XmlElement xeSub = xmlDoc.CreateElement("RunningTime");
                        xeSub.InnerText = tempData[i];
                        xmlElement.AppendChild(xeSub);
                    }
                    else if (i == 12)
                    {
                        XmlElement xeSub = xmlDoc.CreateElement("WaitingTime");
                        xeSub.InnerText = tempData[i];
                        xmlElement.AppendChild(xeSub);
                    }
                    else if (i == 13)
                    {
                        XmlElement xeSub = xmlDoc.CreateElement("SelfCheck");
                        xeSub.InnerText = tempData[i];
                        xmlElement.AppendChild(xeSub);
                    }
                    else if (i == 14)
                    {
                        XmlElement xeSub = xmlDoc.CreateElement("InputQty");
                        xeSub.InnerText = tempData[i];
                        xmlElement.AppendChild(xeSub);
                    }
                    else if (i == 15)
                    {
                        XmlElement xeSub = xmlDoc.CreateElement("Barcode");
                        xeSub.InnerText = tempData[i];
                        xmlElement.AppendChild(xeSub);
                    }
                    else if (i == 16)
                    {
                        XmlElement xeSub = xmlDoc.CreateElement("Model");
                        xeSub.InnerText = tempData[i];
                        xmlElement.AppendChild(xeSub);
                    }
                    else if (i == 17)
                    {
                        XmlElement xeSub = xmlDoc.CreateElement("CT_Q");
                        xeSub.InnerText = tempData[i];
                        xmlElement.AppendChild(xeSub);
                    }
                    else if (i == 18)
                    {
                        XmlElement xeSub = xmlDoc.CreateElement("CT_M");
                        xeSub.InnerText = tempData[i];
                        xmlElement.AppendChild(xeSub);
                    }
                
                    else if (i == 19)
                    {
                        XmlElement xeSub = xmlDoc.CreateElement("PlcMode");
                     
                        xeSub.InnerText = tempData[i];
                        xmlElement.AppendChild(xeSub);
                    }
                    else if (i == 20)
                    {
                        XmlElement xeSub = xmlDoc.CreateElement("ModulusValue");
                        xeSub.InnerText = tempData[i];
                        xmlElement.AppendChild(xeSub);
                    }
                    else if (i == 21)
                    {
                        XmlElement xeSub = xmlDoc.CreateElement("IsEnable");
                        xeSub.InnerText = "1";
                        xmlElement.AppendChild(xeSub);
                    }
                    else if (i == 22)
                    {
                        XmlElement xeSub = xmlDoc.CreateElement("VirtualMachine");
                        xeSub.InnerText = tempData[i-1];
                        xmlElement.AppendChild(xeSub);
                    }
                    else if (i == 23)
                    {
                        XmlElement xeSub = xmlDoc.CreateElement("IsTimeEnable");
                        xeSub.InnerText = tempData[i - 1];
                        xmlElement.AppendChild(xeSub);
                    }
                }

                xmlDoc.Save(Application.StartupPath + @"\Device\" + tempData[0] + ".xml");//保存的路径


                TabPage tempPage = new TabPage();
                DeviceClass tempDevice = new DeviceClass();
                tempDevice.Ip = tempData[0];
                tempDevice.InterfaceID = tempData[1];
                tempDevice.EquipName = tempData[2];
                tempDevice.EquipType = tempData[3];
                tempDevice.Status = tempData[4];
                tempDevice.StatusCode = tempData[5];
                tempDevice.PassQty = tempData[6];
                tempDevice.FailQty = tempData[7];
                tempDevice.ErrorCnt = tempData[8];
                tempDevice.ErrorTimes = tempData[9];
                tempDevice.CycleTime = tempData[10];
                tempDevice.RunningTime = tempData[11];
                tempDevice.WaitingTime = tempData[12];
                tempDevice.SelfCheck = tempData[13];
                tempDevice.InputQty = tempData[14];
                tempDevice.Barcode = tempData[15];
                tempDevice.Model = tempData[16];
                tempDevice.CT_Q = tempData[17];
                tempDevice.CT_M = tempData[18];
                tempDevice.IsEnable = "1";
                tempDevice.PlcMode = tempData[19];
                try
                { tempDevice.ModulusValue = Convert.ToDouble(tempData[20]); }
                catch { }
               
                tempDevice.VirtualMachine = tempData[21];


                if (tempData[22] == "1")
                {
                    tempDevice.IsTimeEnable = true;
                }
                else
                    tempDevice.IsTimeEnable = false;


                tempPage.Text = "✔ " + tempData[0];
                PlcControl tempControl = new PlcControl(tempDevice);
                tempControl.Dock = DockStyle.Fill;
                tempPage.Controls.Add(tempControl);
                deviceUiTabControlMenu.TabPages.Add(tempPage);
                ipAsahDic.Add(tempDevice.Ip, tempControl);
                deviceList.Add(tempDevice);

                ToolStripMenuItem tempTool = new ToolStripMenuItem();
                tempTool.Text = tempDevice.Ip;
                tempTool.Click += TempTool_Click;
                UpdatePLCToolStripMenuItem.DropDownItems.Add(tempTool);

                try
                {
                    string path = Application.StartupPath + @"\Log\" + tempDevice.Ip + ".txt";
                    if (!File.Exists(path))
                    {
                        using (StreamWriter sw = File.CreateText(path))
                        {
                            tempDevice.LogPath = path;
                        }
                    }
                    else
                    {
                        tempDevice.LogPath = path;
                    }
                }
                catch { }

                MessageBox.Show("添加成功");
            }
            else
            {
                FileInfo[] files = di.GetFiles();
             
                foreach (FileInfo item in files)
                {
                    if (item.Extension.ToLower() == ".xml")
                    {
                        if (item.Name.Replace(".xml", "") == tempData[0])
                        {
                            XmlDocument xmlDocument = new XmlDocument();
                            xmlDocument.Load(item.FullName);
                            XmlNodeList xmlNode = xmlDocument.SelectSingleNode("PLCDATA").ChildNodes;

                            foreach (XmlNode node in xmlNode)
                            {
                               if (node.Name == "InterfaceID")
                                {
                                    node.InnerText = tempData[1];
                                    ipAsahDic[tempData[0]].Txt_interfaceID.Text = tempData[1];
                                }
                                else if (node.Name == "EquipName")
                                {
                                    node.InnerText = tempData[2];
                                    ipAsahDic[tempData[0]].uiTextBox1.Text = tempData[2];
                                }
                                else if (node.Name == "EquipType")
                                {
                                    node.InnerText = tempData[3];
                                    ipAsahDic[tempData[0]].Txt_equipType.Text = tempData[3];
                                }
                                else if (node.Name == "Status")
                                {
                                     node.InnerText = tempData[4];
                                    ipAsahDic[tempData[0]].Txt_status.Text = tempData[4];

                                }
                                else if (node.Name == "StatusCode")
                                {
                                    node.InnerText = tempData[5];
                                    ipAsahDic[tempData[0]].Txt_statusCode.Text = tempData[5];
                                }
                                else if (node.Name == "PassQty")
                                {
                                    node.InnerText = tempData[6];
                                    ipAsahDic[tempData[0]].Txt_passQty.Text = tempData[6];
                                }
                                else if (node.Name == "FailQty")
                                {
                                     node.InnerText = tempData[7];
                                    ipAsahDic[tempData[0]].Txt_failQty.Text = tempData[7];
                                }
                                else if (node.Name == "ErrorCnt")
                                {
                                    node.InnerText = tempData[8];
                                    ipAsahDic[tempData[0]].Txt_errorCnt.Text = tempData[8];
                                }
                                else if (node.Name == "ErrorTimes")
                                {
                                    node.InnerText = tempData[9];
                                    ipAsahDic[tempData[0]].Txt_errorTimes.Text = tempData[9];
                                }
                                else if (node.Name == "CycleTime")
                                {
                                     node.InnerText = tempData[10];
                                    ipAsahDic[tempData[0]].Txt_cycleTime.Text = tempData[10];
                                }
                                else if (node.Name == "RunningTime")
                                {
                                    node.InnerText = tempData[11];
                                    ipAsahDic[tempData[0]].Txt_runningTime.Text = tempData[11];
                                }
                                else if (node.Name == "WaitingTime")
                                {
                                     node.InnerText = tempData[12];
                                    ipAsahDic[tempData[0]].Txt_waitingTime.Text = tempData[12];
                                }
                                else if (node.Name == "SelfCheck")
                                {
                                     node.InnerText = tempData[13];
                                    ipAsahDic[tempData[0]].Txt_selfCheck.Text = tempData[13];
                                }
                                else if (node.Name == "InputQty")
                                {
                                     node.InnerText = tempData[14];
                                    ipAsahDic[tempData[0]].Txt_inputQty.Text = tempData[14];
                                }
                                else if (node.Name == "Barcode")
                                {
                                     node.InnerText = tempData[15];
                                    ipAsahDic[tempData[0]].Txt_barcode.Text = tempData[15];
                                }
                                else if (node.Name == "Model")
                                {
                                    node.InnerText = tempData[16];
                                    ipAsahDic[tempData[0]].Txt_model.Text = tempData[16];
                                }
                                else if (node.Name == "CT_Q")
                                {
                                     node.InnerText = tempData[17];
                                    ipAsahDic[tempData[0]].Txt_CT_Q.Text = tempData[17];
                                }
                                else if (node.Name == "CT_M")
                                {
                                     node.InnerText = tempData[18];
                                    ipAsahDic[tempData[0]].Txt_CT_M.Text = tempData[18];
                                }
                                else if (node.Name == "PlcMode")
                                {
                                    node.InnerText = tempData[19];
                                    if (tempData[19] == "0")
                                    { ipAsahDic[tempData[0]].uiTextBox23.Text = "AsAh-Series";} //ipAsahDic[tempData[1]].uiPanel1.Style = UIStyle.Blue;
                                    else if (tempData[19] == "1")
                                    { ipAsahDic[tempData[0]].uiTextBox23.Text = "Dvp-Series";}//ipAsahDic[tempData[1]].uiPanel1.Style = UIStyle.Purple;
                                    else if (tempData[19] == "2")
                                    { ipAsahDic[tempData[0]].uiTextBox23.Text = "HMI";}//ipAsahDic[tempData[1]].uiPanel1.Style = UIStyle.Colorful;

                                }
                                else if (node.Name == "ModulusValue")
                                {
                                    node.InnerText = tempData[20];
                                    ipAsahDic[tempData[0]].uiTextBox3.Text = tempData[20];
                                }
                                else if (node.Name == "VirtualMachine")
                                {
                                    node.InnerText = tempData[21];
                                    ipAsahDic[tempData[0]].uiLabel28.Text = tempData[21];
                                }
                                else if (node.Name == "IsTimeEnable")
                                {
                                    node.InnerText = tempData[22];

                                    if (tempData[22]=="1")
                                    {
                                        ipAsahDic[tempData[0]].uiLabel30.Text = "已启动定时";
                                    }
                                    else
                                    {
                                        ipAsahDic[tempData[0]].uiLabel30.Text = "";
                                    }


                                    //ipAsahDic[tempData[0]].uiLabel30.Text = tempData[21];
                                }
                            }

                            xmlDocument.Save(item.FullName);

                            break;
                        }
                    }
                }


                for (int i = 0; i < deviceList.Count; i++)
                {
                    if (deviceList[i].Ip == tempData[0])
                    {
                        deviceList[i].InterfaceID = tempData[1];
                        deviceList[i].EquipName = tempData[2];
                        deviceList[i].EquipType = tempData[3];

                        deviceList[i].Status = tempData[4];
                        deviceList[i].StatusCode = tempData[5];
                        deviceList[i].PassQty = tempData[6];
                        deviceList[i].FailQty = tempData[7];
                        deviceList[i].ErrorCnt = tempData[8];
                        deviceList[i].ErrorTimes = tempData[9];
                        deviceList[i].CycleTime = tempData[10];
                        deviceList[i].RunningTime = tempData[11];
                        deviceList[i].WaitingTime = tempData[12];
                        deviceList[i].SelfCheck = tempData[13];
                        deviceList[i].InputQty = tempData[14];
                        deviceList[i].Barcode = tempData[15];
                        deviceList[i].Model = tempData[16];
                        deviceList[i].CT_Q = tempData[17];
                        deviceList[i].CT_M = tempData[18];

                        deviceList[i].PlcMode = tempData[19];

                        try
                        { deviceList[i].ModulusValue = Convert.ToDouble(tempData[20]); }
                        catch { }


                        deviceList[i].VirtualMachine = tempData[21];

                        if (tempData[22] == "1")
                        {
                            deviceList[i].IsTimeEnable = true;  
                        }
                        else
                            deviceList[i].IsTimeEnable = false;
                    }
                }


                MessageBox.Show("更新成功");
            }
         
        }

        private void DeletePLCToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (TotalControl)
            {
                MessageBox.Show("运行中禁止删除设备");
                return;
            }
            if (deviceList.Count == 0)
            {
                MessageBox.Show("无设备，请先添加设备");
                return;
            }

            EnableForm ef = new EnableForm(deviceList, 1);
            ef.SaveEvent += Ef_SaveEvent;

            RightForm rf = new RightForm(ef, 0);
            rf.ShowDialog();
        }

        private void StartToolStripMenuItem_Click(object sender, EventArgs e)
        {

            if (deviceList.Count > 0)
            {
                for (int i = 0; i < deviceList.Count; i++)
                {
                    if (deviceList[i].IsEnable == "1")
                    {


                        if (!deviceList[i].IsThreadRun)
                        {
                            deviceList[i].PlcModbus = new ModbusTcp();

                            Thread thread = new Thread(new ParameterizedThreadStart(ipAsahDic[deviceList[i].Ip].ReadPlcThread));
                            thread.Name = deviceList[i].Ip; 
                            thread.IsBackground = true;
                            thread.Start(deviceList[i]);
                            threadList.Add(thread);

                            deviceList[i].IsThreadRun = true;

                        }

                        deviceList[i].IsReadData = true;

                    }
                }

                StartToolStripMenuItem.Enabled = false;

                TotalControl = true;
            }
            else
            {
                MessageBox.Show("无设备数据，请先添加设备");
            }

          
        }
  
        private void StopToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (deviceList.Count > 0)
            {
                for (int i = 0; i < deviceList.Count; i++)
                {
                    if (deviceList[i].IsEnable == "1")
                    {
                      
                        deviceList[i].IsReadData = false;

                   
                    }
                }
            }


            //StopToolStripMenuItem.Enabled = false;
            StartToolStripMenuItem.Enabled = true;
            TotalControl = false;
        }
    
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (TotalControl)
            {
                MessageBox.Show("运行中禁止启用设备");
                return;
            }

            if (deviceList.Count > 0)
            {
                for (int i = 0; i < deviceList.Count; i++)
                {
                    if (deviceList[i].IsEnable != "1")
                    {
                        deviceList[i].IsEnable = "1";


                        foreach (TabPage item in deviceUiTabControlMenu.TabPages)
                        {

                            if (item.Text.Contains("✘"))
                            {
                                if (item.Text.Replace("✘", "").Trim() == deviceList[i].Ip)
                                {
                                    item.Text = "✔ " + deviceList[i].Ip;
                                }
                            }
                        }



                        ipAsahDic[deviceList[i].Ip].uiLabel23.BackColor = Color.Black;
                        ipAsahDic[deviceList[i].Ip].uiLabel23.Text = "设备启用，通讯未连接";

                    }



                    FileInfo[] files = di.GetFiles();

                    foreach (FileInfo item in files)
                    {
                        if (item.Extension.ToLower() == ".xml")
                        {
                            if (item.Name.Replace(".xml", "") == deviceList[i].Ip)
                            {
                                XmlDocument xmlDocument = new XmlDocument();
                                xmlDocument.Load(item.FullName);
                                XmlNodeList xmlNode = xmlDocument.SelectSingleNode("PLCDATA").ChildNodes;

                                foreach (XmlNode node in xmlNode)
                                {
                                    if (node.Name == "IsEnable")
                                    {
                                        node.InnerText = "1";
                                        xmlDocument.Save(item.FullName);
                                        break;
                                    }
                                }

                                break;
                            }
                        }
                    }




                }
            }
            else
            {
                MessageBox.Show("无设备，请先添加设备");
                return;
            }

            MessageBox.Show("启用成功");
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            if (TotalControl)
            {
                MessageBox.Show("运行中禁止禁用设备");
                return;
            }

            if (deviceList.Count > 0)
            {
                for (int i = 0; i < deviceList.Count; i++)
                {
                    if (deviceList[i].IsEnable == "1")
                    {
                        deviceList[i].IsEnable = "0";

                        deviceList[i].IsReadData = false;

                        foreach (TabPage item in deviceUiTabControlMenu.TabPages)
                        {
                            if (!item.Text.Contains("✘"))
                            {
                                if (item.Text.Contains("✔"))
                                {
                                    if (item.Text.Replace("✔", "").Trim() == deviceList[i].Ip)
                                    {
                                        item.Text = "✘ " + deviceList[i].Ip;
                                    }
                                }
                               
                            }
                        }


                       
                            ipAsahDic[deviceList[i].Ip].uiLabel23.BackColor = Color.Gray;
                            ipAsahDic[deviceList[i].Ip].uiLabel23.Text = "设备未启用";
                      
                       
                    }


                    FileInfo[] files = di.GetFiles();

                    foreach (FileInfo item in files)
                    {
                        if (item.Extension.ToLower() == ".xml")
                        {
                            if (item.Name.Replace(".xml", "") == deviceList[i].Ip)
                            {
                                XmlDocument xmlDocument = new XmlDocument();
                                xmlDocument.Load(item.FullName);
                                XmlNodeList xmlNode = xmlDocument.SelectSingleNode("PLCDATA").ChildNodes;

                                foreach (XmlNode node in xmlNode)
                                {
                                    if (node.Name == "IsEnable")
                                    {
                                        node.InnerText = "0";
                                        xmlDocument.Save(item.FullName);
                                        break;
                                    }
                                }

                                break;
                            }
                        }
                    }

                }
            }
            else
            {
                MessageBox.Show("无设备，请先添加设备");
                return;
            }

            MessageBox.Show("禁用成功");
        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            if (TotalControl)
            {
                MessageBox.Show("运行中禁止启用设备");
                return;
            }

            if(deviceList.Count==0)
            {
                MessageBox.Show("无设备，请先添加设备");
                return;
            }

            EnableForm ef = new EnableForm(deviceList,0);
            ef.SaveEvent += Ef_SaveEvent;
            ef.ShowDialog();
        }


        private void Ef_SaveEvent(Dictionary<string, bool> saveDataDic,int mode)
        {
            if (mode == 0)
            {
                for (int i = 0; i < deviceList.Count; i++)
                {
                    if (saveDataDic.ContainsKey(deviceList[i].Ip))
                    {
                        if (saveDataDic[deviceList[i].Ip])
                        {
                            deviceList[i].IsEnable = "1";


                            foreach (TabPage item in deviceUiTabControlMenu.TabPages)
                            {
                                if (item.Text.Contains("✘"))
                                {
                                    if (item.Text.Replace("✘", "").Trim() == deviceList[i].Ip)
                                    {
                                        item.Text = "✔ " + deviceList[i].Ip ;

                                    }
                                }
                            }

                           
                                ipAsahDic[deviceList[i].Ip].uiLabel23.BackColor = Color.Black;
                                ipAsahDic[deviceList[i].Ip].uiLabel23.Text = "设备启用，通讯未连接";
                        


                            FileInfo[] files = di.GetFiles();

                            foreach (FileInfo item in files)
                            {
                                if (item.Extension.ToLower() == ".xml")
                                {
                                    if (item.Name.Replace(".xml", "") == deviceList[i].Ip)
                                    {
                                        XmlDocument xmlDocument = new XmlDocument();
                                        xmlDocument.Load(item.FullName);
                                        XmlNodeList xmlNode = xmlDocument.SelectSingleNode("PLCDATA").ChildNodes;

                                        foreach (XmlNode node in xmlNode)
                                        {
                                            if (node.Name == "IsEnable")
                                            {
                                                node.InnerText = "1";
                                                xmlDocument.Save(item.FullName);
                                                break;
                                            }
                                        }

                                        break;
                                    }
                                }
                            }
                        }
                        else
                        {
                            deviceList[i].IsEnable = "0";

                            deviceList[i].IsReadData = false;

                            foreach (TabPage item in deviceUiTabControlMenu.TabPages)
                            {
                                if (!item.Text.Contains("✘"))
                                {
                                    if (item.Text.Contains("✔"))
                                    {
                                        if (item.Text.Replace("✔", "").Trim() == deviceList[i].Ip)
                                        {
                                            item.Text = "✘ " + deviceList[i].Ip;
                                        }
                                    }

                                }
                            }

                          
                                ipAsahDic[deviceList[i].Ip].uiLabel23.BackColor = Color.Gray;
                                ipAsahDic[deviceList[i].Ip].uiLabel23.Text = "设备未启用";
                           

                            FileInfo[] files = di.GetFiles();

                            foreach (FileInfo item in files)
                            {
                                if (item.Extension.ToLower() == ".xml")
                                {
                                    if (item.Name.Replace(".xml", "") == deviceList[i].Ip)
                                    {
                                        XmlDocument xmlDocument = new XmlDocument();
                                        xmlDocument.Load(item.FullName);
                                        XmlNodeList xmlNode = xmlDocument.SelectSingleNode("PLCDATA").ChildNodes;

                                        foreach (XmlNode node in xmlNode)
                                        {
                                            if (node.Name == "IsEnable")
                                            {
                                                node.InnerText = "0";
                                                xmlDocument.Save(item.FullName);
                                                break;
                                            }
                                        }

                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                for (int i = 0; i < deviceList.Count; i++)
                {
                    if (saveDataDic.ContainsKey(deviceList[i].Ip))
                    {
                        if (saveDataDic[deviceList[i].Ip])
                        {
                            deviceList[i].IsThreadControl = false;

                            foreach (TabPage item in deviceUiTabControlMenu.TabPages)
                            {
                                if (item.Text.Contains("✘"))
                                {
                                    if (item.Text.Replace("✘", "").Trim() == deviceList[i].Ip)
                                    {
                                        deviceUiTabControlMenu.TabPages.Remove(item);

                                        if (ipAsahDic.ContainsKey(deviceList[i].Ip))
                                        {
                                            ipAsahDic.Remove(deviceList[i].Ip);
                                        }

                                        break;
                                    }
                                }
                                else  
                                {
                                    if (item.Text.Contains("✔"))
                                    {
                                        if (item.Text.Replace("✔", "").Trim() == deviceList[i].Ip)
                                        {
                                            deviceUiTabControlMenu.TabPages.Remove(item);

                                            if (ipAsahDic.ContainsKey(deviceList[i].Ip))
                                            {
                                                ipAsahDic.Remove(deviceList[i].Ip);
                                            }


                                            break;
                                        }
                                    }
                                }
                            }

                            FileInfo[] files = di.GetFiles();

                            foreach (FileInfo item in files)
                            {
                                if (item.Name.Replace(".xml", "") == deviceList[i].Ip) 
                                {File.Delete(item.FullName);break; }
                            }


                            foreach (ToolStripDropDownItem item in UpdatePLCToolStripMenuItem.DropDownItems)
                            {
                                if (item.Text.Split('(')[0].Trim() == deviceList[i].Ip)
                                {
                                    UpdatePLCToolStripMenuItem.DropDownItems.Remove(item);
                                    break;
                                }
                            }


                            deviceList.Remove(deviceList[i]);
                            i--;

                           
                            //删除ini

                        }
                     
                    }
                }
            }
            
        }


        private void ChangePwToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PasswordForm pwf = new PasswordForm();
            pwf.pwEvent += Pwf_pwEvent;
            pwf.ShowDialog();
        }

        private void Pwf_pwEvent()
        {
            try
            {
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(timePath);
                XmlNodeList xmlNode = xmlDocument.SelectSingleNode("GlobalParameters").ChildNodes;

                foreach (XmlNode node in xmlNode)
                {
                    if (node.Name.ToLower() == "password")
                    {
                        node.InnerText = Password.ToString();
                        xmlDocument.Save(timePath);
                    }
                }

            }
            catch { MessageBox.Show("数据写入异常"); }
        }


        private void LogToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                Process.Start(Application.StartupPath + @"\Log");
            }
            catch
            { }
        }
        #endregion

        private void timer1_Tick(object sender, EventArgs e)
        {
            uiLabel2.Text =  DateTime.Now.ToString();
            uiLabel3.Text = "admin" + threadList.Count;


            try
            {
                if (TotalControl)
                {
                    string connectState = string.Empty;
                    if (deviceList.Count > 0)
                    {
                        for (int i = 0; i < deviceList.Count; i++)
                        {
                            if (!deviceList[i].IsConnected)
                            {
                                if (deviceList[i].IsThreadRun && deviceList[i].IsEnable == "1")
                                    connectState += deviceList[i].Ip.Split('.')[3] + ",";
                            }
                            else
                            {
                                if (deviceList[i].IsThreadRun && deviceList[i].IsEnable == "1" && deviceList[i].IsError)
                                    connectState += deviceList[i].Ip.Split('.')[3] + ",";
                            }
                        }
                        if (connectState != null && connectState.Length != 0 && connectState != string.Empty && connectState != "")
                        {
                            connectState += "Connected Error";
                            uiLabel4.Text = connectState;
                            uiLabel4.ForeColor = Color.Red;
                        }
                        else
                        {
                            uiLabel4.Text = string.Empty;

                        }
                    }
                    else
                    {
                        uiLabel4.Text = string.Empty;

                    }
                }
              else
                { uiLabel4.Text = string.Empty;}
            }
            catch { }



            try
            {
                string tempStr = "线程状态监控：\r\n";

                for (int i = threadList.Count - 1; i >= 0; i--)
                {
                    tempStr += threadList[i].Name + "："+ threadList[i].IsAlive + "-" + threadList[i].ThreadState + "\r\n";
                    if (!threadList[i].IsAlive)
                    {
                        threadList.RemoveAt(i);
                    }
                }
                uiToolTip1.SetToolTip(pictureBox1, tempStr);
            }
            catch { }



            try
            {
                FileInfo[] files = logDi.GetFiles();

                foreach (FileInfo item in files)
                {
                    if (item.Extension.ToLower() == ".txt")
                    {
                        double logD= PublicClass.ConvertFileSizeToM(item.Length);
                        if (logD > LogSize)
                        {
                            File.WriteAllText(item.FullName, string.Empty);
                        }
                    }
                }
            }
            catch { }

         
            DisposeMemory();

           
        }

        /// <summary>
        /// 内存释放
        /// </summary>
        private void DisposeMemory()
        {
            try
            {
                GC.Collect();

                GC.WaitForPendingFinalizers();

                if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                {

                    SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);

                }
            }
            catch { }

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            RightForm rf = new RightForm(1);
            rf.ShowDialog();
        }
    }




    public class SimulatorDevice
    {
        public string MachineName=string.Empty;

       public List<string> MachineIdList=new List<string>();
    }
}
